<?php

//namespace Home\Controller;

//use Think\Controller;
use Workerman\Worker;

class WorkermanController
{
    public function index()
    {
        if (!IS_CLI) {
            die("无法直接访问，请通过命令行启动");
        }
        $worker = new \Workerman\Worker('websocket://0.0.0.0:2000');
// 当收到客户端发来的数据后返回hello $data给客户端
        $worker->onWorkerStart = function ($worker) {
            echo "Worker starting...\n";
        };
        $worker->onMessage = function ($connection, $data) {
// 向客户端发送hello $data
            $connection->lastMessageTime = time();
            $info = json_decode($data,true);
            if (!isset($connection->uid)) {
                // 没验证的话把第一个包当做uid（这里为了方便演示，没做真正的验证）
                if (!empty($info)) {
                    $user_id = M('UserToken')->getUserIdByAccessToken($info['access_token']);
                    $connection->uid = $user_id;
                    $worker->uidConnections[$info['id']][$connection->uid] = $connection;
                }else {
                }
            }else {

                foreach($worker->uidConnections[$info['id']] as $val)
                {
                    if ($val->uid !=  $connection->uid) {
                        $val->send($data);
                    }
                }
            }
        };
// 运行worker
        Worker::runAll();

    }
}